/**
    Copyright (C) 2011  Alexander Vollmer

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.jefb.web.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;

import org.zkoss.zk.ui.Executions;
import org.zkoss.zul.Filedownload;
import org.zkoss.zul.Tab;
import org.zkoss.zul.Tabbox;
import org.zkoss.zul.Tabpanels;
import org.zkoss.zul.Tabs;

/**
 * @author alexej
 * 
 */
public abstract class ComponentsUtil {

	public static void createEditorTab(Tabbox tabbox, File file) {
		String fileName = file.getName();
		
		//check if a view or editor for current file are already created
		//TODO check by absolute file name
		List<?> children = tabbox.getTabs().getChildren();
		for (Object child : children) {
			if (child instanceof Tab) {
				Tab childTab = (Tab) child;
				if (((Tab) child).getLabel().equalsIgnoreCase(fileName)) {
					tabbox.setSelectedTab(childTab);
					return;
				}
			}
		}

		Tabpanels tabpanels = tabbox.getTabpanels();
		boolean tabCreated = false;
		if (FileType.isAllowedImageFile(fileName)) {
			Executions.createComponentsDirectly("<image_viewer_tabpanel />",
					null, tabpanels, null);
			tabCreated = true;
		} else if (FileType.isAllowedTextFile(fileName)) {
			Executions.createComponentsDirectly("<text_editor_tabpanel />",
					null, tabpanels, null);
			tabCreated = true;
		} else if (fileName.toLowerCase().endsWith(".pdf")) {
			Executions.createComponentsDirectly("<pdf_viewer_tabpanel />",
					null, tabpanels, null);
			tabCreated = true;
		} else {
			try {
				Filedownload.save(file, null);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}

		if (tabCreated) {
			Tabs tabs = tabbox.getTabs();
			Tab newContentTab = new Tab(fileName);
			newContentTab.setClosable(true);
			newContentTab.setImage("../img/fs16/" + Icons.getSrc(fileName));
			newContentTab.setParent(tabs);
			tabbox.setSelectedTab(newContentTab);
		}
	}

}
